package com.bobi.tfca.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobi.tfca.dao.SysResourceDao;
import com.bobi.tfca.model.constant.MailConstant;
import com.bobi.tfca.model.constant.RedisConstant;
import com.bobi.tfca.model.entity.MemberEntity;
import com.bobi.tfca.model.entity.SysResourceEntity;
import com.bobi.tfca.service.MemberService;
import com.bobi.tfca.service.SysResourceService;
import com.bobi.tfca.utils.Generate4NumberUtils;
import com.bobi.tfca.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 系统资源服务层实现
 * @author 李文发
 * @date 2024/4/3
 */
@Service
@Slf4j
public class SysResourceServiceImpl extends ServiceImpl<SysResourceDao, SysResourceEntity> implements SysResourceService {

    @Autowired
    private MemberService memberService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MailUtil mailUtil;

    @Override
    public Boolean sendEmailCode2Exist(String account) {
        // 查询账号的用户
        MemberEntity member = memberService.getOne(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getTelephone, account));

        // 生成验证码
        String checkCode = Generate4NumberUtils.generateCheckCode();
        // 向邮箱发送
        String mailText = String.format(MailConstant.CHECKCODE_MAIL, member.getMemberName(), member.getEmail(), checkCode);
        mailUtil.sendSimpleTextMail(member.getEmail(), MailConstant.DEFAULT_MAIL_SUBJECT, mailText, null);
        // 发送成功存储验证码到redis
        String key = RedisConstant.USER_CAPTCHA_PREFIX + account;
        stringRedisTemplate.opsForValue().set(key, checkCode, Duration.ofMinutes(10));
        return true;
    }

    public Boolean sendEmailCode4Register(String telephone, String email) {
        try {
            // 生成验证码
            String checkCode = Generate4NumberUtils.generateCheckCode();
            // 向邮箱发送
            String mailText = String.format(MailConstant.CHECKCODE_MAIL, email, email, checkCode);
            mailUtil.sendSimpleTextMail(email, MailConstant.DEFAULT_MAIL_SUBJECT, mailText, null);
            // 发送成功存储验证码到redis
            String key = RedisConstant.USER_CAPTCHA_PREFIX + telephone;
            stringRedisTemplate.opsForValue().set(key, checkCode, Duration.ofMinutes(10));
            return true;
        } catch (Exception e) {
            log.error("发送验证码错误", e);
            return false;
        }
    }
}
